import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/user/Users'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/login',
}, {
  path: '/login',
  component: Login,
  meta: {
    title: '登录'
  }
}, {
  path: '/home',
  component: Home,
  redirect: '/home/welcome',
  children: [{
      path: 'welcome',
      component: Welcome,
      meta: {
        title: '主页'
      },
    },
    {
      path: 'users',
      component: Users,
      meta: {
        title: '用户管理'
      },
    }
  ]
}]

const router = new VueRouter({
  routes
})
//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  if (to.path == '/login') return next()
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
  document.title = to.meta.title
})
export default router
